package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
)

type NovelController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NovelController) Get() {
}
func (c *NovelController) Add() {
	file, header, err := c.GetFile("img")
	defer file.Close()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)

	novel_id, _ := c.GetInt("novel_id")
	novel_name := c.GetString("novel_name")
	name := c.GetString("name")
	info := c.GetString("info")
	address := c.GetString("address")
	novel := models.Novel{
		NovelId:   novel_id,
		NovelName: novel_name,
		Name:      name,
		Img:       "http://127.0.0.1:8080/" + path,
		Info:      info,
		Address:   address,
	}
	err = models.DB.Debug().Create(&novel).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *NovelController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	query := models.DB.Model(&models.Novel{}).Count(&count)
	offset := (page - 1) * size
	var novel []models.Novel
	pageData := make(map[string]interface{})
	err := query.Offset(offset).Limit(size).Find(&novel).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		pageData["count"] = count
		pageData["novel"] = novel
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
